
#include "GravBody.h"

/*--------------------------------------------------------------------*/
void GravBody::init(vec3f loc, vec3f vel, float rad, float mass) {
	vLoc = loc;
	vVel = vel;
	fRad = rad;
	fMass = mass;
	fMassSqr = mass*mass;
	fInvMassSqr = 1/fMassSqr;
	maxDetail = (int)(rad*1)+2;
	gGeo = new Geosphere(fRad,maxDetail);
	historyTime = 0;

	InitializeCriticalSection(&historyCS);
}

/*--------------------------------------------------------------------*/
void GravBody::updateWithForce(vec3f f, float timeScale) {
	vVel = addVec(vVel, f);
	vLoc = addVec(vLoc, scaleVec(vVel,timeScale));
}

/*--------------------------------------------------------------------*/
void GravBody::updateHistory(float timePass) {
	historyTime += timePass;
	if ( historyTime > 30 ) { 
		history.push_front(vLoc);
		historyTime = 0;
	}

	// Block this section with a semaphore
	getHistoryAccess(true);

	// Remember three seconds worth of history
	if ( history.size() > 100 ) { history.pop_back(); }

	getHistoryAccess(false);
}

/*--------------------------------------------------------------------*/
const vec3f* GravBody::getLoc() { return &vLoc; }
const vec3f* GravBody::getVel() { return &vVel; }
const float GravBody::getRad() { return fRad; }
const float GravBody::getMass() { return fMass; }
const float GravBody::getMassSqr() { return fMassSqr; }
const float GravBody::getInvMassSqr() { return fInvMassSqr; }
const int GravBody::getMaxDetail() { return maxDetail; }
const list<vec3f>* GravBody::getHistory() { return &history; }
Geosphere* GravBody::getGeosphere() { return gGeo; }

/*--------------------------------------------------------------------*/
vec3f GravBody::getGfxLoc() { return vLoc; }

/*--------------------------------------------------------------------*/
void GravBody::alterTerrain() { gGeo->buildTerrain(); }

/*--------------------------------------------------------------------*/
void GravBody::getHistoryAccess(bool enter) {
	enter ? 
		EnterCriticalSection(&historyCS) : 
		LeaveCriticalSection(&historyCS);
}